package com.hy.common;

import java.io.*;

/**
 * 对文件的操作工具类
 * @author hy
 * @version 1.0 2019/10/7/19:38
 */
public class FileUtils {

    /**
     * 获取一个文件的内容
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String readFile(File file) throws IOException {

        if (file.isFile()) {

            StringBuilder sb = new StringBuilder();

            String temp;

            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            while ((temp = bufferedReader.readLine()) != null) {
                sb.append(temp);
            }

            bufferedReader.close();

            return sb.toString();

        } else {
            throw new IOException("路径 " + file.getPath() + " 不是一个文件。");
        }
    }

    /**
     * 保存字符数据到本地
     *
     * @param str  写出内容
     * @param path 写出路径
     * @throws IOException
     */
    public static void writeFile(String str, File path) throws IOException {

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(path));

        bufferedWriter.write(str);

        bufferedWriter.close();
    }

    /**
     * 保存二进制数据到本地
     *
     * @param bufferedInputStream
     * @param savePath
     */
    public static void writeFile(BufferedInputStream bufferedInputStream, String savePath) throws IOException {

        //根据文件保存地址，创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(savePath);

        //构造缓冲区
        //一次最多读取1k
        byte[] buffer = new byte[1024];
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        //实际读取的长度
        int readLenghth;
        //文件逐步写入本地
        //先读出来，保存在buffer数组中
        while ((readLenghth = bufferedInputStream.read(buffer, 0, 1024)) != -1) {
            //再从buffer中取出来保存到本地
            bufferedOutputStream.write(buffer, 0, readLenghth);
        }
        //关闭缓冲流
        bufferedOutputStream.close();
        fileOutputStream.close();
        bufferedInputStream.close();
    }

    /**
     * 创建目录
     * @param path 路径
     * @return true创建成功，false 失败
     */
    public static boolean mkdir(String path) {
        return FileUtils.mkdir(path, true);
    }


    /**
     * 创建目录
     * @param path              路径
     * @param isCreateParentDir 是否连续创建目录
     * @return true创建成功，false 失败
     */
    public static boolean mkdir(String path, boolean isCreateParentDir) {
        File file = new File(path);
        if (!file.exists()) {
            return isCreateParentDir ? file.mkdirs() : file.mkdir();
        } else {
            //目录存在返回true,相当于已经创建
            return true;
        }
    }

}
